const { task } = require('hardhat/config')

task('deploy-fundme', 'deploy and verify fundme contract').setAction(async (taskArgs, hre) => {
	// create factory
	const fundMeFactory = await ethers.getContractFactory('FundMe')
	console.log('contract deploying...')
	// deploy contract from factory,这里的180会被contract FundMe的构造函数construct所接收，作为参数传入到合约中
	const fundMe = await fundMeFactory.deploy(180)
	// 等待合约部署完成
	await fundMe.waitForDeployment()
	console.log('contract deployed to:', fundMe.target)

	// verify fundMe contract
	console.log(`Network chainId: ${hre.network.config.chainId}`);

	if (hre.network.config.chainId == 11155111 && process.env.ETHERSCAN_API_KEY) {
		console.log('waiting for 5 confirmations...')
		await fundMe.deploymentTransaction().wait(5)

		// 在验证之前先等待一分钟，让 Etherscan 有时间索引新部署的合约
		console.log('Waiting 60 seconds before verification...')
		await new Promise(resolve => setTimeout(resolve, 60000))

		try {
			await verifyFundMe(fundMe.target, [180])
			console.log(`The contract ${fundMe.target} has already been verified on Etherscan`)
		} catch (error) {
			console.log('Verification failed. You can try to verify manually later using:')
			console.log(`npx hardhat verify --network sepolia ${fundMe.target} 180`)
		}
	} else {
		console.log('verification skipped - not on Sepolia network or missing API key')
	}
})

async function verifyFundMe(fundMeAddress, args) {
	try {
		await hre.run('verify:verify', {
			address: fundMeAddress,
			constructorArguments: args,
		})
	} catch (error) {
		// 如果合约已经被验证，这不算作错误
		if (error.message.includes('Already Verified')) {
			console.log('Contract is already verified!')
			return
		}
		throw error
	}
}

module.exports = {}
